# -*- coding: utf-8 -*-
# @Author	: brotherbaby
# @Date		: 2023/10/25 10:08
# @Last Modified by:   brotherbaby
# @Last Modified time: 2023/10/25 10:08
# Thanks for your comments!
import logging

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

from src.db_proxy.models import *
from src.db_proxy.models.modelbase import ModelBase
from src.utils.singleton import singleton


@singleton
class DbConnector(object):
    def __init__(self, db_conf):
        self.engine = create_engine(
            f"mysql+pymysql://{db_conf['user']}:{db_conf['pwd']}@{db_conf['host']}:{db_conf['port']}/{db_conf['db']}",
            pool_size=5,
            pool_timeout=10,
            pool_pre_ping=True,
            pool_recycle=3600,
            encoding='utf-8')
        logging.info(f"{db_conf['db']} connected.")
        ModelBase.metadata.create_all(self.engine, checkfirst=True)

    def get_session(self):
        Session = sessionmaker(bind=self.engine)
        session_ins = scoped_session(Session)
        return session_ins

    def close_session(self, session_ins):
        session_ins.close()
